//==============================================================================
//
// Title:       RXGhainGain .c
// Purpose:     A short description of the implementation.
//
// Created on:  2013-3-1 at 15:00:35 by Vinson.Zhang
// Copyright:   dafda. All Rights Reserved.
//
//==============================================================================

#include "rssmb.h"
#include "RFBB.h"         
#include <utility.h>
#include <formatio.h>	  
//#include "hpesg.h"
#include "SetSignalGenerator.h"


                             
_SHMON_RX_CHAIN_GAIN_CMD g_szShmonRxChainGainCmd[12] ={
        {"\n" ,"RX_chain_gain_H_Pipe1.txt",0.0,0.0},
		{"\n" ,"RX_chain_gain_M_Pipe1.txt",0.0,0.0},
		{"\n" ,"RX_chain_gain_L_Pipe1.txt",0.0,0.0},
        {"\n" ,"RX_chain_gain_H_Pipe2.txt",0.0,0.0},
		{"\n" ,"RX_chain_gain_M_Pipe2.txt",0.0,0.0}, 
		{"\n" ,"RX_chain_gain_L_Pipe2.txt",0.0,0.0}, 
        {"\n" ,"RX_chain_gain_H_Pipe3.txt",0.0,0.0},
		{"\n" ,"RX_chain_gain_M_Pipe3.txt",0.0,0.0}, 
		{"\n" ,"RX_chain_gain_L_Pipe3.txt",0.0,0.0}, 
		{"\n" ,"RX_chain_gain_H_Pipe4.txt",0.0,0.0},
		{"\n" ,"RX_chain_gain_M_Pipe4.txt",0.0,0.0},
        {"\n" ,"RX_chain_gain_L_Pipe4.txt",0.0,0.0}};


/**************************************************************************************************
  Function:        RXGhainGain
  Description:     This test is the tests the lock detect status of all synthesizers.
  Calls:           none
  Called By:       dll
  Table Accessed:  none
  Table Updated:   none
  Input:           none
  Output:          error code
  Return:          none
  Test Case ID:    FAHA_DigTRX_BIST_SYNTH
  Used Command:    g_szCmonSynOfLock
**************************************************************************************************/
void __decldllexp TX_TEST RXGhainGain(tTestData *testData, tTestError *testError)
{

    ErrMsg errMsg = {'\0'};
    ViStatus viStatus; // For esgErrChk -macro
    ERRORINFO errorInfo;   
    ErrMsg szLogMsg;
    CAObjHandle hStepName = 0;
    char* pszStepName = NULL;
	char* SCRIPT_FILE_PATH = NULL;	//add by Vinson
    char kszShmonAgent[BUFFER_SIZE_256] ={'\0'};   
    char szElementPath[BUFFER_SIZE_256] ={'\0'};
    double dTestNum = 0.0;
    double dFrequency = 0.0;
    double dRxGain = -99.9;
    int  error = 0;
    int  iPassFail = 0;
    int i = 0;
    int iPipeNum = 0;
    int iReturn = 0;
    double dCableOffset = 0.0;
    //////////////////////////////////////////////////////////////////////////   
    // Resolve StepName 
    tsErrChk(TS_SeqContextGetProperty (testData->seqContextCVI, &errorInfo, 
                                       TS_SeqContextStep, CAVT_OBJHANDLE, 
                                       &hStepName));
    tsErrChk(TS_StepGetProperty (hStepName, &errorInfo, TS_StepName, CAVT_CSTRING, 
                                 &pszStepName));

    sprintf( szLogMsg, TEST_NAME_EVENT_FMTSTR, pszStepName );
    ErrChk( EELog_INEventLogLogEvent( g_hEventLog, NULL, szLogMsg ) );

    // Post message to GUI
    tsErrChk(TS_ThreadPostUIMessageEx (g_hThreadPostUIMessage, NULL,
                                       TS_UIMsg_ProgressText, 0.0,
                                       pszStepName, 0, VTRUE));    

    //--------------------------------------------------------------------
    // Get Test Parameters from Sequence FileGlobals   

    sprintf(szElementPath, "%s.%s.PARAMETERS.TestFrequency", TESTPLAN_BASE_PATH, pszStepName );   
    tsErrChk(TS_PropertyGetValNumber(testData->seqContextCVI, &errorInfo, szElementPath, 0, &dFrequency));
    
    sprintf(szElementPath, "%s.%s.PARAMETERS.TestNum", TESTPLAN_BASE_PATH, pszStepName );   
    tsErrChk(TS_PropertyGetValNumber(testData->seqContextCVI, &errorInfo, szElementPath, 0, &dTestNum));
    sprintf(szElementPath, "%s.%s.PARAMETERS.CableOffset", TESTPLAN_BASE_PATH, pszStepName );   
    tsErrChk(TS_PropertyGetValNumber(testData->seqContextCVI, &errorInfo, szElementPath, 0, &dCableOffset));
	
	//Get SCRIPT_FILE_PATH from TestPlan Head    
    sprintf( szElementPath, "%s.PARAMETERS.SCRIPT_FILE_PATH", TESTPLAN_BASE_PATH_EXT );
    tsErrChk(TS_PropertyGetValString (testData->seqContextCVI, &errorInfo, szElementPath, 0, &SCRIPT_FILE_PATH));
    //-------------------------------------------------------------------- 	

    if((dTestNum >= 0) && (dTestNum < 12))
    	{
        i = dTestNum;
    	}

	//Fulfill Struct
	sprintf(kszShmonAgent, "%s\\%s", SCRIPT_FILE_PATH, g_szShmonRxChainGainCmd[i].cRemoteFileName);
	strcpy(g_szShmonRxChainGainCmd[i].cLocalFilePath, kszShmonAgent);
	
    // Setup signal generator
	rssmb_confRFFreq (g_hSignalGenerator, dFrequency*1e6, 0.0, VI_FALSE, 1.0e6);
	rssmb_SetRFLevelLimit (g_hSignalGenerator, -40.0);
	rssmb_SetOutputState (g_hSignalGenerator, VI_TRUE);
	
    
    Delay(2.5); // some delay to let ESG level settle   
    
    //FTP upload script files
    iReturn = RfbbInetFTPAutoSend(g_szDUTIP, "", "", g_szShmonRxChainGainCmd[i].cLocalFilePath, g_szShmonRxChainGainCmd[i].cRemoteFileName, INET_FTP_FILE_TYPE_BINARY);    
    if(iReturn < 0)
    {
        sprintf( szLogMsg, STRING_MESSAGE_Ftp_File_Err, g_szDUTIP, InetGetErrorMessage( iReturn ) );
        EELog_INEventLogLogEvent (g_hEventLog, NULL, szLogMsg);
        
        goto Error;
    } 

	//InetTelnetOpen(ShellCommand)  
    g_hShellCommand = RfbbInetTelnetOpen (g_szDUTIP, g_iShellCommandPort, 0); 

    //run script    
    sprintf(kszShmonAgent,". %s",g_szShmonRxChainGainCmd[i].cRemoteFileName);
    Shmon_RunScript(kszShmonAgent,5);    
   
    
    //send shell command and compare return value 
    iPipeNum = i / 3;
    sprintf(kszShmonAgent,"fpga -MERA%d -r 0x18006",(iPipeNum + 1));
    ErrChk(ShellCommand_HexNumeric(kszShmonAgent, -1,"Read ",&g_szShmonRxChainGainCmd[i].dGetAdcPow)); 				  
    
    sprintf(kszShmonAgent,"fpga -MERA%d -r 0x1A040",(iPipeNum + 1));
    ErrChk(ShellCommand_HexNumeric(kszShmonAgent, -1,"Read ",&g_szShmonRxChainGainCmd[i].dGetCorrectFact));


    //dRxGain = 10 * log10((g_szShmonRxChainGainCmd[i].dGetValue +  1) / 4718592) + 2.6 + 50.0 + dCableOffset;
    dRxGain = 10 * log10((g_szShmonRxChainGainCmd[i].dGetAdcPow+  1) / ((g_szShmonRxChainGainCmd[i].dGetCorrectFact * g_szShmonRxChainGainCmd[i].dGetCorrectFact) / 8))+ 6 + 40.0 + dCableOffset;

    sprintf( szLogMsg, "the RX Gain is %.3f" ,dRxGain);
    EELog_INEventLogLogEvent (g_hEventLog, NULL, szLogMsg);

Error:
    
#if(ON_OFF != SIMU_VERS) 

	//SG turn off
	rssmb_SetOutputState (g_hSignalGenerator, VI_FALSE);
	rssmb_SetRFLevelLimit (g_hSignalGenerator, -100.0);

    if(iPassFail == 1)
    {
        testData->result = PASS;
    }
    else 
    {
        testData->result = FAIL;
    }
    
    testData->measurement = dRxGain;

	//InetTelnetClose(ShellCommand)
    InetTelnetClose(g_hShellCommand);
	
    // FREE RESOURCES
    CA_DISCARD_OBJ( hStepName );
    CA_FREE( pszStepName );
	CA_FREE( SCRIPT_FILE_PATH );

    // If an error occurred, set the error flag to cause a run-time error in TestStand.
    if(error < 0)
    {
        testError->errorFlag = TRUE;
        testError->errorCode = error;
        testData->replaceStringFuncPtr(&testError->errorMessage, errMsg);
    }
#else
    testData->result = PASS;
#endif

   // Clear message from GUI
   TS_ThreadPostUIMessageEx (g_hThreadPostUIMessage, NULL,
                                 TS_UIMsg_ProgressText, 0.0, " ", 0, VTRUE);

   return;    
}

/**************************************************************************************************
  Function:        RXGhainGainInit
  Description:     This test is the tests the lock detect status of all synthesizers.
  Calls:           none
  Called By:       dll
  Table Accessed:  none
  Table Updated:   none
  Input:           none
  Output:          error code
  Return:          none
  Test Case ID:    FAHA_DigTRX_BIST_SYNTH
  Used Command:    g_szCmonSynOfLock
**************************************************************************************************/
void __decldllexp TX_TEST RXGhainGainInit(tTestData *testData, tTestError *testError)
{

    ErrMsg errMsg = {'\0'};
    ERRORINFO errorInfo;   
    ErrMsg szLogMsg;
    CAObjHandle hStepName = 0;
    char* pszStepName = NULL;
    char kszShmonAgent[BUFFER_SIZE_256] ={'\0'};   
    char szElementPath[BUFFER_SIZE_256] ={'\0'};
    double dTestNum = 0.0;
    int  error = 0;
    int  iPassFail = 1;
    int i = 0;
    int iPipeNum = 0;
    int iReturn = 0;
     char szOutputMessage[BUFFER_SIZE_256] = {'\0'};
    //////////////////////////////////////////////////////////////////////////   
    // Resolve StepName 
    tsErrChk(TS_SeqContextGetProperty (testData->seqContextCVI, &errorInfo, 
                                       TS_SeqContextStep, CAVT_OBJHANDLE, 
                                       &hStepName));
    tsErrChk(TS_StepGetProperty (hStepName, &errorInfo, TS_StepName, CAVT_CSTRING, 
                                 &pszStepName));

    sprintf( szLogMsg, TEST_NAME_EVENT_FMTSTR, pszStepName );
    ErrChk( EELog_INEventLogLogEvent( g_hEventLog, NULL, szLogMsg ) );

    // Post message to GUI
    tsErrChk(TS_ThreadPostUIMessageEx (g_hThreadPostUIMessage, NULL,
                                       TS_UIMsg_ProgressText, 0.0,
                                       pszStepName, 0, VTRUE));

    //--------------------------------------------------------------------
    // Get Test Parameters from Sequence FileGlobals    
    sprintf(szElementPath, "%s.%s.PARAMETERS.TestNum", TESTPLAN_BASE_PATH, pszStepName );   
    tsErrChk(TS_PropertyGetValNumber(testData->seqContextCVI, &errorInfo, szElementPath, 0, &dTestNum));

    if((dTestNum >= 0) && (dTestNum < 4))
    {
        i = dTestNum;
    }   

    
    sprintf(szOutputMessage,"please connect the RX RF-cable on Pipe%d",(i + 1));
    MessagePopup("RX Ghain Gain Test", szOutputMessage);
    
Error:
    
#if(ON_OFF != SIMU_VERS) 
    
    if(iPassFail == 1)
    {
        testData->result = PASS;
    }
    else 
    {
        testData->result = FAIL;
    }

    //InetTelnetClose(g_hShellCommand); 
    // FREE RESOURCES
    CA_DISCARD_OBJ( hStepName );
    CA_FREE( pszStepName );

    // If an error occurred, set the error flag to cause a run-time error in TestStand.
    if(error < 0)
    {
        testError->errorFlag = TRUE;
        testError->errorCode = error;
        testData->replaceStringFuncPtr(&testError->errorMessage, errMsg);
    }
#else
    testData->result = PASS;
#endif

   // Clear message from GUI
   TS_ThreadPostUIMessageEx (g_hThreadPostUIMessage, NULL,
                                 TS_UIMsg_ProgressText, 0.0, " ", 0, VTRUE);

   return;    
}

